#!/usr/bin/python
import xml.etree.ElementTree as ET
import os
import sys

def is_ascii(s):
    return all(ord(c) < 128 for c in s)
	
def main (arg = None):
	
	country_code_to_country_map = {}
	

	with open ("countrylist.csv", "r") as country_list_file:
		for line in country_list_file:
			c_code, c_name = line.strip().split(',')
			country_code_to_country_map[c_code] = Country (c_name, c_code)
	
	with open ("maxmind-region-codes.csv", "r") as region_list_file:
		i = 1

		for line in region_list_file:
			c_code = line[0:2]
			r_code = line[3:5]
			r_name = line[6:].strip()
			country_code_to_country_map[c_code].add_region (r_name, r_code)

	with open ("citylist.csv", "r") as city_list_file:
		i = 1
		for line in city_list_file:
			line_splitted = line.split (',')
			c_code = line_splitted[0].upper()
			r_code = line_splitted[3].upper()
			city_name = line_splitted[2]
			#print str(i) + " " + c_code + " " + r_code 
			try:
				country_code_to_country_map[c_code].regions[r_code].cities.append (city_name)
				
			except:
				sys.stderr.write("Unable to map city: " + line_splitted[4] + " " + line.strip() + "\r\n")
				#pass
				
		
	
	root = ET.Element('CountryList')
	
	print ("<CountryList>")

	for c_code in country_code_to_country_map.keys():
		print ("\t<Country>")
		country = country_code_to_country_map[c_code]
		country_e = ET.SubElement(root,'Country')
		country_name_e = ET.SubElement(country_e,'Name')
		country_name_e.text = country.name
		
		print ("\t\t<Name>" + country.name + "</Name>")
		
		if (len(country.regions.keys()) == 0):
			country.add_region ("Other", "OT")
		
		for r_code in country.regions.keys():
			print ("\t\t<Region>")
			region = country.regions[r_code]
			
			if (len(region.cities) == 0):
				region.cities.append ("Other")
			
			region_e = ET.SubElement(country_e,'Region')
			region_name_e = ET.SubElement(region_e,'Name')
			region_name_e.text = region.name
						
			cities_e = ET.SubElement(region_e,'Cities')
			cities_e.text = ",".join (region.cities)
			
			print ("\t\t\t<Name>" + region.name + "</Name>")
			print ("\t\t\t<Cities>" + ",".join(region.cities) + "</Cities>")
			print ("\t\t</Region>")
		print ("\t</Country>")
	tree = ET.ElementTree(root)
	#tree.write("out4.xml",encoding="UTF-16",xml_declaration=True)
	
	print ("</CountryList>")
	
class Country:
    def __init__ (self, name, code):
        self.name = name
        self.code = code	
        self.regions = {}
		
    def add_region(self, name, code):
        self.regions[code] = Region (name, code)

class Region:
    def __init__ (self, name, code):
        self.name = name
        self.code = code	
        self.cities = []
		
if __name__ == '__main__':
  main()